package com.project.common.core.utils.id;

import com.project.common.core.utils.exception.BaseCustomException;
import org.apache.commons.lang3.StringUtils;

/**
 * 条形码工具类
 */
public class LineCodeWorker {

    /**
     * 根据条形码值生成计算后的条形码
     *
     * @param lineCode
     * @return
     */
    public static String encode(String lineCode) {
        char[] chars = lineCode.toCharArray();
        int code = 0;
        for (char c : chars) {
            code = (c - '0') + code;
        }
        return lineCode + (code % 10);
    }

    /**
     * 根据条形码还原为系统条形码
     *
     * @param lineCode
     * @return
     */
    public static String decode(String lineCode) {
        if (StringUtils.isNotBlank(lineCode)) {
            lineCode = lineCode.trim();
            int len = lineCode.length();
            if (len > 1) {
                String preNo = lineCode.substring(0, len - 1);
                if (lineCode.equals(encode(preNo))) {
                    return preNo;
                }
            }
        }
        throw new BaseCustomException("verifyLineCode Error", "条形码错误!");
    }

}
